package com.magist.manage.web.controller;

import com.magist.core.constants.AppConstants;
import com.magist.core.constants.ResultMessageCode;
import com.magist.core.controller.BaseController;
import com.magist.core.entity.ResultMessage;
import com.magist.core.helper.SessionHelper;
import com.magist.core.util.Base64;
import com.magist.core.util.ImageUtil;
import com.magist.manage.web.dto.LoginDto;
import com.magist.manage.web.dto.UserInfoDto;
import com.magist.manage.web.facade.IndexFacade;
import com.magist.manage.web.facade.UserFacade;
import com.magist.manage.web.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@Api(value = "基础接口", tags = {"基础接口"})
@Controller
@RequestMapping("/rest")
public class RestIndexController extends BaseController {

    @Autowired
    private SessionHelper sessionHelper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private IndexFacade indexFacade;
    @Autowired
    private UserFacade userFacade;

    @ApiOperation(value = "登录接口", notes = "用户登录接口")
    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@ApiParam(name = "loginDto", value = "loginDto") @RequestBody LoginDto loginDto) {
        ResultMessage result = ResultMessage.success();
        Assert.hasLength(loginDto.getLoginName(), "登录名为空");
        Assert.hasLength(loginDto.getPassword(), "密码为空");
        UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getLoginName(), loginDto.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        result.setContent(subject.getSession().getId().toString());
        return result;
    }

    @ApiOperation(value = "获取用户信息", notes = "根据token获取用户信息")
    @RequestMapping(value = "info.do", method = RequestMethod.GET)
    @ResponseBody
    public Object info(@ModelAttribute("token") String token, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultMessage result = ResultMessage.success();
        SessionKey key = new WebSessionKey(token, request, response);
        Session se = SecurityUtils.getSecurityManager().getSession(key);
        Object obj = se.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (obj != null) {
            SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
            UserInfoDto userInfo = (UserInfoDto) coll.getPrimaryPrincipal();
            userInfo.setPassword(null);
            //获取用户菜单
            userInfo.setMenuString(indexFacade.getUserMenuString(userInfo.getId()));
            userInfo.setMenuOpString(indexFacade.getUserMenuOpString(userInfo.getId()));
            result.setContent(userInfo);
        }else{
            result = ResultMessage.error("token信息不存在");
            result.setCode(ResultMessageCode.ERROR_TOKEN);

        }
        return result;
    }

    @ApiOperation(value = "退出", notes = "退出")
    @RequestMapping(value = "logout.do", method = RequestMethod.GET)
    @ResponseBody
    public Object logout(@ModelAttribute("token") String token, HttpServletRequest request, HttpServletResponse response) throws IOException {
        SessionKey key = new WebSessionKey(token, request, response);
        Session se = SecurityUtils.getSecurityManager().getSession(key);
        se.removeAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        return ResultMessage.success();
    }

//    @ApiOperation(value="测试接口", notes="测试接口")
//    @RequestMapping(value = "testInfo.do", method = RequestMethod.GET)
//    @ResponseBody
//    public Object testInfo(@ModelAttribute("token") String token) {
//        userFacade.testUser();
//        ResultMessage result = ResultMessage.success();
//        result.setContent("");
//        return result;
//    }

    @ApiOperation(value = "验证码接口", notes = "获取验证码")
    @RequestMapping(value = "checkCode.do", method = RequestMethod.GET)
    @ResponseBody
    public Object checkCode() throws IOException {
        ResultMessage result = ResultMessage.success();
        Random random = new Random();
        String rands = "";
        for (int i = 0; i < 4; i++) {
            rands = rands + random.nextInt(10);
        }
        // 保存 值 到 session
        sessionHelper.set(AppConstants.SESSION_LOGIN_CHECKCODE_KEY, rands);
        //字节流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//字节输出流
        // 生成图片
        BufferedImage image = ImageUtil.createImage(rands);
        ImageIO.write(image, "JPEG", baos);
        byte[] content = baos.toByteArray();
        result.setContent(Base64.encode(content));
        return result;
    }
}
